<?
	set_magic_quotes_runtime (FALSE);
	ini_set('magic_quotes_gpc', 0);
	error_reporting(E_ERROR);
	session_start();
	header ('Content-type: text/html; charset=utf-8');   
	require_once "../db/connection.inc"; 
	include_once "JSON.php";
	$action = $_REQUEST["action"];
	
	$json = new Services_JSON(); 
	
	$tableName = $_REQUEST['table'];
	
	if("$action"=="list"){
		
		$sql = "select Id,Tipo,Descrizione from  $tableName order by Tipo" ;
		$dt =rs($sql);
		 
		exit( recordsetToJson($dt,0)  );
	
	} else if("$action"=="delete"){
		$postedData = str_replace( '##','"',$_REQUEST['data']); 
		$data = $json->decode($postedData); 
		$record = $data[0]; 
		
		if($record->Id=='' )	exit("{updated : [0],  status : 'OK', message:'Nessun record da cancellare' } ");	
		$db = db();	 
		
		$sql = "DELETE FROM $tableName WHERE Id=$record->Id" ;	
		$res = $db->query($sql); 
		 
		if(!$res) 	exit("{updated : [],  status : 'ERRORS', message:'Errore Durante l'eliminazione' } "); 
		else 		exit("{updated : [0],  status : 'OK', message:'Deleted' } ");		
		
				
	} else if("$action"=="save"){
		
		/* oggetto scambiato
			
			{
				updated : [0,1,..n],
				status : 'OK|ERRORS',
				message:''
			}
			
		*/
		
		$postedData = str_replace( '##','"',$_REQUEST['data']); 
  
		$data = $json->decode($postedData); 
		$db = db();	 
		
		for($i=0;$i<sizeof($data);$i++){
			$record = $data[$i];  
			$Row = $record->_Row_  ; 
			  
			if($record->Tipo=="") { 
				$updateErrors["$Row"] = "Tipo Necessario\\n"  ; 
				continue;
			}
 	
			if($record->Descrizione=="") {	 
				$updateErrors["$Row"].= "Descrizione Necessaria"  ;
				continue;
			}
			
			$Tipo = $db->quoteSmart($record->Tipo)  ;
			$Descrizione = $db->quoteSmart($record->Descrizione)  ;
			
			 
			if( $record->Id >0 ) { 
				$sql = "UPDATE $tableName  SET Tipo=$Tipo , Descrizione=$Descrizione where Id=$record->Id" ;	
					
			}else{
				$sql = "INSERT INTO $tableName  ( Tipo , Descrizione) values ($Tipo , $Descrizione ) " ;
			}
			
			
			$res = $db->query($sql); 
			
			
			if(!$res) $updateErrors["$Row"] = "Errore salvando il record"  ; 	
			else $updatedRows[] = $Row;		
			
		}	 
	 
		if($i==0) exit("{updated : [], status : 'ERRORS', message:'Nessun Dato Trovato' } ");
		
		$updatedStr = join($updatedRows,',');
		
		if( isset($updateErrors) ){
			 
			foreach($updateErrors as $rowdt => $val){
				$realRow = $rowdt+1;
				 
				$errorMessage.= "<b>Riga $realRow</b> non completa <br>" ; 
			};
			
			exit("{updated : [$updatedStr],  status : 'ERRORS', message:'$errorMessage' } ");
		}
		else exit("{updated : [$updatedStr],  status : 'OK', message:'Saved' } ");
	}
	
	echo "Dati non memorizzati a causa di un errore (action='$action') ";	
	
?>